import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score

# 设置字体为支持中文的字体
plt.rcParams['font.family'] = 'SimHei'  # 或者使用 'AR PL UKai CN'
plt.rcParams['axes.unicode_minus'] = False  # 用于正常显示负号

# 生成数据
np.random.seed(42)
X = np.sort(5 * np.random.rand(100, 1), axis=0)  # 特征
y = np.sin(X).ravel() + np.random.normal(0, 0.1, X.shape[0])  # 目标值

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化随机森林回归模型
rf_regressor = RandomForestRegressor(n_estimators=100, random_state=42)

# 训练模型
rf_regressor.fit(X_train, y_train)

# 预测
y_pred = rf_regressor.predict(X_test)

# 评估模型
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"均方误差 (MSE): {mse:.4f}")
print(f"决定系数 (R²): {r2:.4f}")

# 可视化
plt.figure(figsize=(10, 6))
plt.scatter(X_train, y_train, color='blue', label='训练数据')
plt.scatter(X_test, y_test, color='green', label='测试数据')
plt.plot(X_test, y_pred, color='red', linewidth=2, label='随机森林预测')
plt.xlabel('X')
plt.ylabel('y')
plt.title('随机森林回归示例')
plt.legend()
plt.show()